# -*- coding: UTF-8 -*-
"""
@Project ：black-white-site-remote 
@File    ：auto_speed.py
@IDE     ：PyCharm 
@Author  ：Tang
@Date    ：2021/10/16 15:36 
"""
import time
from functools import wraps
from urllib.parse import urlparse

from rest_framework.response import Response

from configer import LOG
from url_control.models import BlackHouse


def speed_limit_middleware(func):
    """访问速度限制"""

    @wraps(func)
    def wrapper(self, request, *args, **kwargs):
        limit_cache = 5
        limit_num = 30
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]  #所以这里是真实的ip
        else:
            ip = request.META.get('REMOTE_ADDR')  #这里获得代理ip
        # LOG.info(f"速度限制访问ip：--> {str(ip)}")
        possible_ = BlackHouse.objects.filter(host=ip)
        if possible_.exists():
            one_possible = possible_[0]
            if one_possible.invalid:  # 被封禁
                res = {"message": '由于违反本站协议 您已被永久封禁 如有疑问请联系作者 （1092824310@qq.com）', "code": 30001}
            elif one_possible.free_time:
                if time.time() > one_possible.free_time:
                    one_possible.free_time = 0
                    res = func(self, request, *args, **kwargs)
                else:
                    res = {"message": '您已被暂时封禁5min 过段时间再来吧', "code": 30001}
                    one_possible.free_time = int(time.time()) + (limit_cache * 60)
                    one_possible.valid_level += 1
                    if one_possible.valid_level > 10:  # 如果level大于10 将被封禁
                        one_possible.invalid = 1
            elif one_possible.has_count:  # 还有访问次数
                res = func(self, request, *args, **kwargs)
                one_possible.has_count -= 1
            else:
                res = {"message": '访问过于频繁 您的风险操作将被记录 多次记录可能导致您被封禁', "code": 30001}
                one_possible.free_time = int(time.time()) + (limit_cache * 60)
            if time.time() - one_possible.last_time > 30:  # 与上次访问时间大于30 则自动更新剩余次数
                one_possible.has_count = limit_num
            one_possible.control_num += 1
            one_possible.last_time = time.time()
            one_possible.save()
        else:
            BlackHouse(host=ip).save()
            res = func(self, request, *args, **kwargs)
        return res if isinstance(res, Response) else Response(res)

    return wrapper


def log_middleware(func):
    """日志记录"""

    @wraps(func)
    def wrapper(self, request, *args, **kwargs):
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]  #所以这里是真实的ip
        else:
            ip = request.META.get('REMOTE_ADDR')  #这里获得代理ip
        url = urlparse(request.get_full_path()).path
        LOG.info(f'访问ip： {ip}  访问地址: {url}')
        res = func(self, request, *args, **kwargs)
        return res if isinstance(res, Response) else Response(res)

    return wrapper
